<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge" >
  <title>WKWebView离线缓存 | Grx Blog</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <meta name="description" content="WKWebView离线缓存相信使用过webView的人都挺烦每次都有一段空白期，用户体验感极差，所以公司要求在webView上增加缓存，废话不多说了，进入正题！">
<meta property="og:type" content="article">
<meta property="og:title" content="WKWebView离线缓存">
<meta property="og:url" content="http://yoursite.com/2018/10/10/WKWebView离线缓存/index.html">
<meta property="og:site_name" content="Grx Blog">
<meta property="og:description" content="WKWebView离线缓存相信使用过webView的人都挺烦每次都有一段空白期，用户体验感极差，所以公司要求在webView上增加缓存，废话不多说了，进入正题！">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/6955990-10287e9178b484ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/497">
<meta property="og:updated_time" content="2018-10-11T06:58:03.490Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="WKWebView离线缓存">
<meta name="twitter:description" content="WKWebView离线缓存相信使用过webView的人都挺烦每次都有一段空白期，用户体验感极差，所以公司要求在webView上增加缓存，废话不多说了，进入正题！">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/6955990-10287e9178b484ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/497">
  
    <link rel="alternative" href="/atom.xml" title="Grx Blog" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png">
  
  <link rel="stylesheet" href="/css/style.css">
</head>

<body>
  <div id="container">
    <div class="left-col">
    <div class="overlay"></div>
<div class="intrude-less">
	<header id="header" class="inner">
		<a href="/" class="profilepic">
			
			<img lazy-src="/img/rufei.jpg" class="js-avatar">
			
		</a>

		<hgroup>
		  <h1 class="header-author"><a href="/">Grx</a></h1>
		</hgroup>

		
		<p class="header-subtitle">自我管理，知识管理，时间管理，阅读，语音写作，思维导图</p>
		

		
			<div class="switch-btn">
				<div class="icon">
					<div class="icon-ctn">
						<div class="icon-wrap icon-house" data-idx="0">
							<div class="birdhouse"></div>
							<div class="birdhouse_holes"></div>
						</div>
						<div class="icon-wrap icon-ribbon hide" data-idx="1">
							<div class="ribbon"></div>
						</div>
						
						<div class="icon-wrap icon-link hide" data-idx="2">
							<div class="loopback_l"></div>
							<div class="loopback_r"></div>
						</div>
						
						
						<div class="icon-wrap icon-me hide" data-idx="3">
							<div class="user"></div>
							<div class="shoulder"></div>
						</div>
						
					</div>
					
				</div>
				<div class="tips-box hide">
					<div class="tips-arrow"></div>
					<ul class="tips-inner">
						<li>菜单</li>
						<li>标签</li>
						
						<li>友情链接</li>
						
						
						<li>关于我</li>
						
					</ul>
				</div>
			</div>
		

		<div class="switch-area">
			<div class="switch-wrap">
				<section class="switch-part switch-part1">
					<nav class="header-menu">
						<ul>
						
							<li><a href="/">主页</a></li>
				        
							<li><a href="/tags/life">随笔</a></li>
				        
							<li><a href="/archives">所有文章</a></li>
				        
						</ul>
					</nav>
					<nav class="header-nav">
						<div class="social">
							
								<a class="github" target="_blank" href="https://github.com/ruixiaoguo" title="github">github</a>
					        
								<a class="weibo" target="_blank" href="https://weibo.com/u/3984935859?refer_flag=1005055010_" title="weibo">weibo</a>
					        
								<a class="rss" target="_blank" href="#" title="rss">rss</a>
					        
								<a class="zhihu" target="_blank" href="#" title="zhihu">zhihu</a>
					        
						</div>
					</nav>
				</section>
				
				
				<section class="switch-part switch-part2">
					<div class="widget tagcloud" id="js-tagcloud">
						<a href="/tags/OC/" style="font-size: 10px;">-OC</a> <a href="/tags/Android/" style="font-size: 10px;">Android</a> <a href="/tags/Apple-Watch/" style="font-size: 10px;">Apple Watch</a> <a href="/tags/Flutter/" style="font-size: 13.33px;">Flutter</a> <a href="/tags/Life/" style="font-size: 10px;">Life</a> <a href="/tags/Lottie/" style="font-size: 10px;">Lottie</a> <a href="/tags/MMKV/" style="font-size: 10px;">MMKV</a> <a href="/tags/MonkeyKing/" style="font-size: 10px;">MonkeyKing</a> <a href="/tags/OC/" style="font-size: 20px;">OC</a> <a href="/tags/RAC/" style="font-size: 11.67px;">RAC</a> <a href="/tags/Swift/" style="font-size: 15px;">Swift</a> <a href="/tags/WKWebView/" style="font-size: 10px;">WKWebView</a> <a href="/tags/WebView/" style="font-size: 10px;">WebView</a> <a href="/tags/Xcode/" style="font-size: 18.33px;">Xcode</a> <a href="/tags/appledoc/" style="font-size: 10px;">appledoc</a> <a href="/tags/hexo/" style="font-size: 11.67px;">hexo</a> <a href="/tags/ios/" style="font-size: 10px;">ios</a> <a href="/tags/life/" style="font-size: 16.67px;">life</a> <a href="/tags/xcode/" style="font-size: 10px;">xcode</a>
					</div>
				</section>
				
				
				
				<section class="switch-part switch-part3">
					<div id="js-friends">
					
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.devtang.com">唐巧的博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://beyondvincent.com">破船之家</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://limboy.me">无网不剩</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://msching.github.io">码农人生</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://yulingtianxia.com">玉令天下</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.leichunfeng.com">雷纯锋的技术博客</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://jax.cnblogs.com">包建强</a>
			        
			          <a target="_blank" class="main-nav-link switch-friends-link" href="http://blog.cnbang.net">bang</a>
			        
			        </div>
				</section>
				

				
				
				<section class="switch-part switch-part4">
				
					<div id="js-aboutme">知识管理，时间管理，自我管理，阅读，语音写作，思维导图，Wiz，TimeMeter</div>
				</section>
				
			</div>
		</div>
	</header>				
</div>

    </div>
    <div class="mid-col">
      <nav id="mobile-nav">
  	<div class="overlay">
  		<div class="slider-trigger"></div>
  		<h1 class="header-author js-mobile-header hide">Grx</h1>
  	</div>
	<div class="intrude-less">
		<header id="header" class="inner">
			<div class="profilepic">
			
				<img lazy-src="/img/rufei.jpg" class="js-avatar">
			
			</div>
			<hgroup>
			  <h1 class="header-author">Grx</h1>
			</hgroup>
			
			<p class="header-subtitle">自我管理，知识管理，时间管理，阅读，语音写作，思维导图</p>
			
			<nav class="header-menu">
				<ul>
				
					<li><a href="/">主页</a></li>
		        
					<li><a href="/tags/life">随笔</a></li>
		        
					<li><a href="/archives">所有文章</a></li>
		        
		        <div class="clearfix"></div>
				</ul>
			</nav>
			<nav class="header-nav">
				<div class="social">
					
						<a class="github" target="_blank" href="https://github.com/ruixiaoguo" title="github">github</a>
			        
						<a class="weibo" target="_blank" href="https://weibo.com/u/3984935859?refer_flag=1005055010_" title="weibo">weibo</a>
			        
						<a class="rss" target="_blank" href="#" title="rss">rss</a>
			        
						<a class="zhihu" target="_blank" href="#" title="zhihu">zhihu</a>
			        
				</div>
			</nav>
		</header>				
	</div>
</nav>

      <div class="body-wrap"><article id="post-WKWebView离线缓存" class="article article-type-post" itemscope itemprop="blogPost">
  
    <div class="article-meta">
      <a href="/2018/10/10/WKWebView离线缓存/" class="article-date">
  	<time datetime="2018-10-10T10:28:47.000Z" itemprop="datePublished">2018-10-10</time>
</a>
    </div>
  
  <div class="article-inner">
    
      <input type="hidden" class="isFancy" />
    
    
      <header class="article-header">
        
  
    <h1 class="article-title" itemprop="name">
      WKWebView离线缓存
    </h1>
  

      </header>
      
      <div class="article-info article-info-post">
        
	<div class="article-tag tagcloud">
		<ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/WKWebView/">WKWebView</a></li></ul>
	</div>

        

        <div class="clearfix"></div>
      </div>
      
    
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="WKWebView离线缓存"><a href="#WKWebView离线缓存" class="headerlink" title="WKWebView离线缓存"></a>WKWebView离线缓存</h2><p>相信使用过webView的人都挺烦每次都有一段空白期，用户体验感极差，所以公司要求在webView上增加缓存，废话不多说了，进入正题！<br><a id="more"></a></p>
<h3 id="1-使用WKWebView"><a href="#1-使用WKWebView" class="headerlink" title="1.使用WKWebView"></a>1.使用WKWebView</h3><pre><code>// 1.简单创建WKWebView
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 20, self.view.frame.size.width, self.view.frame.size.height - 20)];
webView.navigationDelegate = self;
[self.view addSubview:webView];
// 2.创建请求
NSURL *URL = [NSURL URLWithString:@&quot;xxxxxxxxx&quot;];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:URL];
// 3.加载网页
[webView loadRequest:request];
</code></pre><h3 id="2-最重要的部分来了，重写NSURLProtocol"><a href="#2-最重要的部分来了，重写NSURLProtocol" class="headerlink" title="2.最重要的部分来了，重写NSURLProtocol"></a>2.最重要的部分来了，重写NSURLProtocol</h3><p>思路逻辑：</p>
<p>  使用webView加载页面的时候，如果有缓存，就先加载缓存，没有就请求网络，然后使用系统自带的缓存方式存储；当重新请求网络，就算下与最近一次网络请求相隔有没一个小时，有的话就重新请求网络。这边借用下一大神的图片</p>
<p><img src="https://upload-images.jianshu.io/upload_images/6955990-10287e9178b484ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/497" alt="avatar"></p>
<p>我们这边继续使用大神写好的一个自定义的NSURLProtocol。<br>使用方法是：</p>
<ul>
<li><p>1、pod ‘JWNetAutoCache’</p>
</li>
<li><p>2、在需要开启的时候调用</p>
<p>[JWCacheURLProtocol startListeningNetWorking];</p>
</li>
<li><p>3、使用结束后调用：</p>
<p>[JWCacheURLProtocol cancelListeningNetWorking];</p>
</li>
</ul>
<p>然而这个对于WKWebView来说，它是不走NSURLProtocol的，看到这，惊不惊喜，意不意外！！！不过别急，离成功就差一步了。当然，关于UIWebView的更详细操作请看UIWebview使用缓存并且保证实时性,</p>
<h3 id="3-让WKWebView走NSURLProtocol"><a href="#3-让WKWebView走NSURLProtocol" class="headerlink" title="3.让WKWebView走NSURLProtocol"></a>3.让WKWebView走NSURLProtocol</h3><p>  在 WKWebView 中的请求只是象征性走</p>
<p>+(BOOL) canInitWithRequest:(NSURLRequest *)request<br>之后的整个请求流程似乎就与 NSURLProtocol 完全无关了，但是在UIWwbView中确是正常的，不过由于我之前在WKWebView的代理中实现了一些东西，所以没改变使用WKWebView。一开始一脸懵逼，不懂为啥，不过幸亏在一大神那得到了解决方法，由于大神说的很详细，所以我这边就不重述了(呼呼，其实是我自己也讲不太清楚)。</p>
<p>下面来操作一番：</p>
<ul>
<li><p>1、先下载一大神写的NSURLProtocold的分类<a href="https://github.com/LiuShuoyu/HybirdWKWebVIew/" target="_blank" rel="external">NSURLProtocol+WKWebVIew</a></p>
</li>
<li><p>2、然后在viewDidLoad里通过注册把http和https请求交给NSURLProtocol处理。</p>
<pre><code>[NSURLProtocol wk_registerScheme:@&quot;http&quot;];
[NSURLProtocol wk_registerScheme:@&quot;https&quot;];
</code></pre></li>
</ul>
<p>到目前为止，可以说是大功告成了。关于这一方面的，想了解更多的请看<a href="https://www.jianshu.com/p/4fc13d4d5607" target="_blank" rel="external">iOS WKWebView (NSURLProtocol)拦截js、css，图片资源</a>。</p>
<p>参考文献：<br><a href="https://www.jianshu.com/p/4fc13d4d5607" target="_blank" rel="external">iOS WKWebView (NSURLProtocol)拦截js、css，图片资源</a><br><a href="https://www.jianshu.com/p/69468d0587b6" target="_blank" rel="external">UIWebview使用缓存并且保证实时性</a></p>

      
    </div>
    
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2018/10/11/ios字体适配的三种实现方法/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption"><</strong>
      <div class="article-nav-title">
        
          iOS字体适配的三种实现方法
        
      </div>
    </a>
  
  
    <a href="/2018/09/25/微信高性能通用key-value组件MMKV/" id="article-nav-older" class="article-nav-link-wrap">
      <div class="article-nav-title">微信高性能通用key-value组件MMKV</div>
      <strong class="article-nav-caption">></strong>
    </a>
  
</nav>

  
</article>


<div class="share_jia">
	<!-- JiaThis Button BEGIN -->
	<div class="jiathis_style">
		<span class="jiathis_txt">Share to: &nbsp; </span>
		<a class="jiathis_button_facebook"></a> 
    <a class="jiathis_button_twitter"></a>
    <a class="jiathis_button_plus"></a> 
    <a class="jiathis_button_tsina"></a>
		<a class="jiathis_button_cqq"></a>
		<a class="jiathis_button_douban"></a>
		<a class="jiathis_button_weixin"></a>
		<a class="jiathis_button_tumblr"></a>
    <a href="http://www.jiathis.com/share" class="jiathis jiathis_txt jtico jtico_jiathis" target="_blank"></a>
	</div>
	<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=1405949716054953" charset="utf-8"></script>
	<!-- JiaThis Button END -->
</div>






<div class="duoshuo">
	<!-- 多说评论框 start -->
	<div class="ds-thread" data-thread-key="WKWebView离线缓存" data-title="WKWebView离线缓存" data-url="http://yoursite.com/2018/10/10/WKWebView离线缓存/"></div>
	<!-- 多说评论框 end -->
	<!-- 多说公共JS代码 start (一个网页只需插入一次) -->
	<script type="text/javascript">
	var duoshuoQuery = {short_name:"true"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0] 
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
	</script>
	<!-- 多说公共JS代码 end -->
</div>




</div>
      <footer id="footer">
  <div class="outer">
    <div id="footer-info">
    	<div class="footer-left">
    		&copy; 2019 Grx
    	</div>
      	<div class="footer-right">
      		<a href="http://hexo.io/" target="_blank">Hexo</a>  Theme <a href="https://github.com/litten/hexo-theme-yilia" target="_blank">Yilia</a> by Litten
      	</div>
    </div>
  </div>
</footer>
    </div>
    
  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">


<script>
	var yiliaConfig = {
		fancybox: true,
		mathjax: true,
		animate: true,
		isHome: false,
		isPost: true,
		isArchive: false,
		isTag: false,
		isCategory: false,
		open_in_new: false
	}
</script>
<script src="http://7.url.cn/edu/jslib/comb/require-2.1.6,jquery-1.9.1.min.js"></script>
<script src="/js/main.js"></script>






<script type="text/x-mathjax-config">
MathJax.Hub.Config({
    tex2jax: {
        inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
        processEscapes: true,
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    }
});

MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
    for(i=0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';                 
    }       
});
</script>

<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  </div>
</body>
</html>